package ajax.quanxuan.sys.controller;

import ajax.quanxuan.sys.entity.Dept;
import ajax.quanxuan.sys.entity.Permission;
import ajax.quanxuan.sys.entity.User;
import ajax.quanxuan.sys.service.PermissionService;
import ajax.quanxuan.sys.service.RoleService;
import ajax.quanxuan.sys.service.UserService;
import ajax.quanxuan.sys.utils.SystemConstant;
import ajax.quanxuan.sys.utils.TreeNodeBuilder;
import ajax.quanxuan.vo.DataGridViewResult;
import ajax.quanxuan.vo.JSONResult;
import ajax.quanxuan.vo.PermissionVo;
import ajax.quanxuan.vo.TreeNode;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("sys/menu")
public class MenuController {
    @Resource
    private PermissionService permissionService;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping("loadIndexLeftMenuTree")
    public DataGridViewResult loadIndexLeftMenuTree(HttpSession session, Permission permission1) {

        //从session获取当前用户
        User loginUser = (User) session.getAttribute(SystemConstant.LOGINUSER);
        //创建集合保存权限菜单
        List<Permission> permissionList = new ArrayList<Permission>();
        //判断当前用户的角色是什么
        //用户类型为0表示当前用户是超级管理员  可以查询所有的功能菜单
        if (loginUser.getType() == SystemConstant.SUPERUSER) {
            //调用查询权限菜单列表的方法
            permissionList = permissionService.listMunleft(permission1);
        } else {
            //根据当前登录用户ID查询该用户的角色列表 获取roleId
            Set<Integer> currentUserRoleIds = userService.findUserRoleByUserId(loginUser.getId());
            //创建set集合保存每个角色下拥有的权限菜单id pids是菜单id
            Set<Integer> pids = new HashSet<>();
            //循环遍历当前有用的角色列表
            for (Integer roleId : currentUserRoleIds) {
                //根据角色id查询角色下拥有的权限菜单 获取菜单id
                Set<Integer> parmisslonIds = roleService.findRoleParmissionByRoleId(roleId);
                pids.addAll(parmisslonIds);
            }
            String pidlist ="";
            //判断当前权限集合是否有数据
            if (pids != null && pids.size() > 0) {
                //凭接查询条件 pids是菜单的id
                for (Integer pids1 : pids) {
                    pidlist += pids1 + ",";
                }
                pidlist = pidlist.substring(0, pidlist.length() - 1);

                permissionList = permissionService.listrolemun(pidlist);

            }
        }
        //创建集合  保存树节点
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        //循环遍历权限菜单列表
        for (Permission permission : permissionList) {
            Boolean spread = SystemConstant.OPEN_TRUE == permission.getOpen() ? true : false;
            TreeNode treeNode = new TreeNode();
            treeNode.setId(permission.getId());//菜
            // 单节点id
            treeNode.setPid(permission.getPid());//菜单父节点编号
            treeNode.setHref(permission.getHref());//菜单路径
            treeNode.setIcon(permission.getIcon());//菜单图标
            treeNode.setTitle(permission.getTitle());//菜单名称
            treeNode.setSpread(spread);//是否展开
            //将树节点的对象添加到树节点的集合
            treeNodes.add(treeNode);
        }
        //构建层级关系
        List<TreeNode> treeNodeList = TreeNodeBuilder.build(treeNodes, 1);
        return new DataGridViewResult(treeNodeList);
    }

    /**
     * 菜单列表
     *
     * @param permissionVo
     * @return
     */
    @RequestMapping("menulist")
    public DataGridViewResult menulist(PermissionVo permissionVo,Permission permission) {

        Long count= Long.valueOf(permissionService.countmenu(permission));
        //返回数据
        return new DataGridViewResult(count, permissionService.listMun(permission));
    }

    @RequestMapping("/loadMenuTreeLeft")
    public DataGridViewResult loadMenuTreeLeft(Permission permission1) {


        //查询所有菜单
        List<Permission> menuList = permissionService.listMunleft(permission1);
        //创建节点集合
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        //循环遍历所有菜单
        for (Permission permission : menuList) {
            //如果状态为1，节点为展开状态
            Boolean spread = permission.getOpen() == SystemConstant.OPEN_TRUE ? true : false;
            //封装树节点
            TreeNode treeNode = new TreeNode();
            treeNode.setId(permission.getId());//菜单编号
            treeNode.setPid(permission.getPid());//父级菜单编号
            treeNode.setTitle(permission.getTitle());//菜单名称
            treeNode.setSpread(spread);//展开状态
            //将树节点对象添加到节点集合
            treeNodes.add(treeNode);
        }
        //将树节点集合返回
        return new DataGridViewResult(treeNodes);
    }

    /**
     * 添加菜单
     *
     * @param permission
     * @return
     */
    @RequestMapping("/addMenu")
    public JSONResult addMenu(Permission permission) {
        //指定type为menu菜单类型
        permission.setType(SystemConstant.TYPE_MENU);
        if (permissionService.save(permission)) {
            return SystemConstant.ADD_SUCCESS;
        }
        return SystemConstant.ADD_ERROR;
    }

    /**
     * 修改菜单
     *
     * @param permission
     * @return
     */
    @RequestMapping("/updateMenu")
    public JSONResult updateMenu(Permission permission) {
        if (permissionService.updateById(permission)) {
            return SystemConstant.UPDATE_SUCCESS;
        }
        return SystemConstant.UPDATE_ERROR;
    }

    /**
     * 检查当前菜单下是否存在子节点
     *
     * @param id
     * @return
     */
    @RequestMapping("/checkMenuHasChildren")
    public String checkMenuHasChildren(int id) {
        Map<String, Object> map = new HashMap<String, Object>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
        //根据父节点查询
        queryWrapper.eq("pid", id);
        //统计菜单数量
        int count = permissionService.count(queryWrapper);
        if (count > 0) {
            //存在子节点
            map.put(SystemConstant.EXIST, true);
            map.put(SystemConstant.MESSAGE, "对不起，当前菜单下有子节点，无法删除！");
        } else {
            //不存在子节点
            map.put(SystemConstant.EXIST, false);
        }
        //将map集合转换成json
        return JSON.toJSONString(map);
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    public JSONResult deleteById(int id) {
        if (permissionService.removeById(id)) {
            return SystemConstant.DELETE_SUCCESS;
        } else {
            return SystemConstant.DELETE_ERROR;
        }
    }
}
